package com.augmentum.springcloudproductservice.service;

import com.augmentum.springcloudproductservice.dto.ProductDto;
import com.augmentum.springcloudproductservice.entity.ProductInfo;
import com.augmentum.springcloudproductservice.enums.ProductStatusEnum;
import com.augmentum.springcloudproductservice.exception.ProductException;
import com.augmentum.springcloudproductservice.repository.ProductInfoRepository;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class ProductInfoService {
    @Resource
    private ProductInfoRepository productInfoRepository;
    public List<ProductInfo> findUpAllProductInfo() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getStatus());
    }

    public void decreaseStock(List<ProductDto> productDtos) {
        productDtos.forEach(productDto -> {
            Optional<ProductInfo> optionalProductInfo = productInfoRepository.findById(productDto.getProductId());
            if (!optionalProductInfo.isPresent()) {
                throw new ProductException(HttpStatus.BAD_REQUEST.value());
            }

            ProductInfo productInfo = optionalProductInfo.get();
            if (productInfo.getProductStock() < productDto.getProductQuantity()) {
                throw new ProductException(400, "No enough stock.");
            }

            productInfo.setProductStock(productInfo.getProductStock() - productDto.getProductQuantity());
            productInfoRepository.save(productInfo);
        });
    }
}
